<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport">
    <title>LayIM 3.x PC版本地演示test</title>
    <script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
    <script src="https://cdn.bootcss.com/jquery/2.2.3/jquery.min.js"></script>
    <link href="./static/css/layui.css" rel="stylesheet">
    <script type="text/javascript" src="./static/js/date.js"></script>

    <style>
        html {
            background-color: #333;
        }
    </style>
    <script src="app.js"></script>
</head>

<body>
<script src="./static/layui.js"></script>
<script src="./json/init.js"></script>
<script>
	if (!/^http(s*):\/\//.test(location.href)) {
		alert('请部署到localhost上查看该演示');
	}

	localStorage.chatHistory = '123'
	const log = console.log.bind(console);

	layui.use('layim', function (layim) {
		log('layui.use layim', layim)
		// 请求基本用户数据
		let initData = {
			id: initConfig().username
		}
		$.post(`http://192.168.1.132:7777/im/getFriendsInfo`, initData, initRes => {
			log('-----/im/getFriendsInfo', initRes)
			if(initRes.success == true) {
				log('init success')
			}
		}).then((initRes) => {
			initRes = initRes.obj
			//基础配置
			layim.config({
				// 初始化时后端应返回群列表及所对应的 socket room 列表， 从前端进行join
				//初始化接口
				init: initRes,				//查看群员接口

				members: {
					url: 'json/getMembers.json',
					data: {}
				},
				//上传图片接口
				uploadImage: {
					url: 'http://192.168.1.132:7777/im/getImFile' //（返回的数据格式见下文）
					,
					type: '' //默认post
				},
				//上传文件接口
				uploadFile: {
					url: '/upload/file' //（返回的数据格式见下文）
					,
					type: '' //默认post
				},
				isAudio: true //开启聊天工具栏音频
				,
				isVideo: true //开启聊天工具栏视频
				//扩展工具栏
				,
				tool: [{
					alias: 'code',
					title: '代码',
					icon: '&#xe64e;'
				}]
				// ,brief: true //是否简约模式（若开启则不显示主面板）
				//,title: 'WebIM' //自定义主面板最小化时的标题
				//,right: '100px' //主面板相对浏览器右侧距离
				//,minRight: '90px' //聊天面板最小化时相对浏览器右侧距离
				,
				initSkin: '5.jpg' //1-5 设置初始背景
				//,skin: ['aaa.jpg'] //新增皮肤
				//,isfriend: false //是否开启好友
				//,isgroup: false //是否开启群组
				//,min: true //是否始终最小化主面板，默认false
				,
				notice: true //是否开启桌面消息提醒，默认false
				//,voice: false //声音提醒，默认开启，声音文件为：default.mp3
				,
				// msgbox: layui.cache.dir + 'css/modules/layim/html/msgbox.html' //消息盒子页面地址，若不开启，剔除该项即可
				msgbox: layui.cache.dir + '../msgbox.html' //消息盒子页面地址，若不开启，剔除该项即可
				,
				find: layui.cache.dir + '../find.html' //发现页面地址，若不开启，剔除该项即可
				,
				chatLog: layui.cache.dir + '../chatlog.html' //聊天记录页面地址，若不开启，剔除该项即可
			});
			log('debug cache', layim.cache());
			let {ip, port, username, password} = initConfig()
			socket = new WebSocket("ws:" + ip + ":" + port + "?username=" + username + "&password=" + password);
			socket.onopen = function () {
				console.log('socket.onopen');
			};
			socket.onmessage = function (e, im=layim) {
				log('socket.onmessage e', e)
				var data = e.data;
				var dataObj = eval("("+data+")");//转换为json对象
				log('onmessage dataObj', dataObj)
				log('11')
				if(dataObj.command == 11){//接收到聊天响应处理;
					log('12 COMMAND_CHAT_RESP')
					COMMAND_CHAT_RESP(dataObj, im);
				}else if(dataObj.command == 18){//获取用户信息响应处理;
					log('13')
					COMMAND_GET_USER_RESP(dataObj);
				}else if(10000 == dataObj.code && dataObj.command == 12){//聊天发送状态;
					log('14 COMMAND_CHAT_RESP_SEND_STATUS')
					COMMAND_CHAT_RESP_SEND_STATUS(data);
				}else if(dataObj.command == 9){//加入群组的消息通知处理;
					log('15 COMMAND_JOIN_GROUP_NOTIFY_RESP')
					COMMAND_JOIN_GROUP_NOTIFY_RESP(dataObj);
				}else if(dataObj.command == 10){
					log('16 COMMAND_EXIT_GROUP_NOTIFY_RESP')
					COMMAND_EXIT_GROUP_NOTIFY_RESP(dataObj);
				}else if(dataObj.command == 20 && dataObj.code == 10015){
					//获取消息失败，未开启持久化处理
					//...
					log('获取消息失败， 未开启持久化处理')
				}else if(dataObj.command == 20 && dataObj.code == 10016){//处理离线消息;
					var msgFlag = "离线消息";
					log('17 COMMAND_GET_MESSAGE_RESP')
					COMMAND_GET_MESSAGE_RESP(dataObj,msgFlag);
				}else if(dataObj.command == 20 && dataObj.code == 10018){//处理历史消息;
					log('18')
					var msgFlag = "历史消息";
					var msgObj = dataObj.data;
					if(msgObj){
						COMMAND_GET_MESSAGE_RESP(dataObj,msgFlag);
					}else{//没有历史消息;
						OTHER(data);
					}
				}else if(dataObj.command == 6){//登陆命令返回状态处理
					log('19 COMMAND_LOGIN_RESP', data)
					COMMAND_LOGIN_RESP(dataObj,data);
				}else{
					OTHER(data);
				}
				// scrollToBottom();

			};
			socket.onerror = function (e) {
				log('socket.error', e)
			};
			socket.onclose = function (e) {
				log('socket.onclose', e)
			};

			//演示自动回复
			var autoReplay = [
				`测试自动回复功能
              By Feng`
			];

			//监听在线状态的切换事件
			layim.on('online', function (data) {
				//console.log(data);
			});

			//监听签名修改
			layim.on('sign', function (value) {
				log('修改签名为: ', value)
				//console.log(value);
			});

			//监听自定义工具栏点击，以添加代码为例
			layim.on('tool(code)', function (insert) {
				layer.prompt({
					title: '插入代码',
					formType: 2,
					shade: 0
				}, function (text, index) {
					layer.close(index);
					insert('[pre class=layui-code]' + text + '[/pre]'); //将内容插入到编辑器
				});
			});

			//监听layim建立就绪
			layim.on('ready', function (res) {
				console.log('ready', res);
				layim.msgbox(5); //模拟消息盒子有新消息，实际使用时，一般是动态获得
				//添加好友（如果检测到该socket）
				layim.addList({
					type: 'group',
					avatar: "http://tva3.sinaimg.cn/crop.64.106.361.361.50/7181dbb3jw8evfbtem8edj20ci0dpq3a.jpg",
					groupname: 'Angular开发',
					id: "12333333",
					members: 0
				});
				layim.addList({
					type: 'friend',
					avatar: "http://tp1.sinaimg.cn/1571889140/180/40030060651/1",
					username: '聊天测试',
					groupid: 2,
					id: "1233333312121212",
					remark: "tes11111t"
				});
			});

			//监听发送消息
			layim.on('sendMessage', function (data) {
				var To = data.to;
				log('data', data);
				if (To.type === 'friend') {
					let msg = {
						from: data.mine.id,
						to: data.to.id,
						cmd: 11,
						createTime: new Date().getTime(),
						chatType:"2",
						msgType: "0",
						content: data.mine.content
					}
					log('私聊', JSON.stringify(msg));
					socket.send(JSON.stringify(msg));
				}
				if (To.type === 'group') {
					let msg = {
						from: data.mine.id,
						group_id: data.to.id,
						cmd: 11,
						createTime: new Date().getTime(),
						chatType:"1",
						msgType: "0",
						content: data.mine.content
					}
					log('群聊', JSON.stringify(msg));
					socket.send(JSON.stringify(msg));
				}
			});

			//监听查看群员
			layim.on('members', function (data) {
				console.log('members', data);
			});

			//监听聊天窗口的切换
			layim.on('chatChange', function (res) {
				var type = res.data.type;
				console.log('当前聊天窗口为', res.data.username);
				if (type === 'friend') {
					//模拟标注好友状态
					//layim.setChatStatus('<span style="color:#FF5722;">在线</span>');
				} else if (type === 'group') {
					//模拟系统消息
					// 	layim.getMessage({
					// 		system: true,
					// 		id: res.data.id,
					// 		type: "group",
					// 		content: '模拟群员' + (Math.random() * 100 | 0) + '加入群聊'
					// 	});
				}
			});
			//登陆通知处理
			function COMMAND_LOGIN_RESP(dataObj,data){
				if(10007 == dataObj.code){//登陆成功;
					log('COMMAND_LOGIN_RESP 10007', data)
					var userCmd = "{\"cmd\":17,\"type\":\"0\",\"userid\":\""+username+"\"}";
					var msgCmd = "{\"cmd\":19,\"type\":\"0\",\"userId\":\""+username+"\"}";
					socket.send(userCmd);//获取登录用户信息;
					socket.send(msgCmd);//获取用户离线消息(好友+群组);
				}else if(10008 == dataObj.code){//登录失败;
					OTHER(data);
				}
			}
			// 离开群组消息通知
			function COMMAND_EXIT_GROUP_NOTIFY_RESP(data){
				log("COMMAND_EXIT_GROUP_NOTIFY_RESP", data)
				var exitGroupNotify = data.data;
				var onlineUserCmd = "{\"cmd\":17,\"type\":\"0\",\"userid\":\""+curUser.id+"\"}";
				socket.send(onlineUserCmd);//获取在线用户列表;
			}
			//加入群组的消息通知处理;
			function COMMAND_JOIN_GROUP_NOTIFY_RESP(data){
				log('COMMAND_JOIN_GROUP_NOTIFY_RESP', data)
				var joinGroupNotify = data.data;
				var onlineUserCmd = "{\"cmd\":17,\"type\":\"0\",\"userid\":\""+curUser.id+"\"}";
				socket.send(onlineUserCmd);//获取在线用户列表;
			}
			//加入群组响应状态处理;
			function COMMAND_JOIN_GROUP_RESP(data){
				//成功加入群组响应信息;
			}
			//发送聊天请求发送状态处理;
			function COMMAND_CHAT_RESP_SEND_STATUS(data){
				//发送成功后的状态处理...
			}
			//获取用户信息响应处理;
			function COMMAND_GET_USER_RESP(data){
				log('COMMAND_GET_USER_RESP', data)
				var user =  data.data;
				curUser = user;
				// initOnlineUsers();
			}

			// 转换接受聊天的格式
			const formatChatMessage = (chatObj) =>{
			    let type = chatObj.hasOwnProperty('group_id') ? 'group' : 'friend'
				log('format type', type)
				log('chatObj', chatObj)
				let reply = {}
				if (type == 'friend') {
					let user = initRes[type][0].list.find((e) => {
						return e.id == chatObj.from
					})
					reply = {
						username: user.username,
						avatar: user.avatar,
						id: chatObj.from,
						type: type,
						content: chatObj.content,
					}
					log('进入 friend reply', reply)
				} else if (type == 'group') {
			    	let group = initRes[type].find((e) => {
			    		if(e.id == chatObj.group_id) {
			    			return e
                        }
                    })
                    log('group', initRes[type])
					let user = initRes['friend'][0].list.find((e) => {
						return e.id == chatObj.from
					})
					reply = {
						username: user.username,
						groupname: group.groupname,
						avatar: user.avatar,
						id: chatObj.group_id,
						type: type,
						members: chatObj.members,
						content: chatObj.content
					}
				}
				return reply
			}

			//接收到聊天响应处理;
			function COMMAND_CHAT_RESP(data, layim){
				log('COMMAND_CHAT_RESP', data)
				log('COMMAND_CHAT_RESP layim', layim)
				var chatObj = data.data;
				var createTime = new Date(chatObj.createTime).Format("yyyy/MM/dd HH:mm:ss");
				var from = chatObj.from;
				// log('from == username', from == username)
				// 页面显示接收消息所需的数据
				let replyOne = formatChatMessage(chatObj, 'friend')
				log('repalyOne', replyOne)
				layim.getMessage(replyOne)
			}
			//处理用户同步+持久化消息
			function COMMAND_GET_MESSAGE_RESP(data,msgFlag){
				log('COMMAND_GET_MESSAGE_RESP data,', data, 'msgFlag', msgFlag)
				var msgObj = data.data;
				friendOfflineMessage(msgObj,msgFlag);
				groupOfflineMessage(msgObj,msgFlag);
			}
			//好友消息
			function friendOfflineMessage(msgObj,msgFlag){
				log('friendOfflineMessage 好友消息 msgObj', msgObj)
				log('friendOfflineMessage 好友消息 msgFlag', msgFlag)
				var friends = msgObj.friends;
				for (var key in friends) {
					var chatDatas = friends[key];
					for(var index in chatDatas){
						var user_id = chatDatas[index].from;
						var createTime = new Date(chatDatas[index].createTime).Format("yyyy/MM/dd HH:mm:ss");
						logDiv.innerHTML+="<font color='	#009ACD' size='1' style='font-weight: bold'>"+user_id+"</font><font color='#DC143C' size='1' style='font-weight: bold'>(好友"+msgFlag+")</font>"+"<font color='#009ACD' size='1' style='font-weight: bold'>"+createTime+"</font><br>";
						logDiv.innerHTML+="<font color='#FFFFFF' size='1'>&nbsp;"+chatDatas[index].content+"</font><br>";
					}
				}
			}
			//群组消息
			function groupOfflineMessage(msgObj,msgFlag){
				log('groupOfflineMessage 群组消息 msgObj', msgObj)
				log('groupOfflineMessage 群组消息 msgFlag', msgFlag)
				var groups = msgObj.groups;
				for (var key in groups) {
					var chatDatas = groups[key];
					for(var index in chatDatas){
						var user_id = chatDatas[index].from;
						var createTime = new Date(chatDatas[index].createTime).Format("yyyy/MM/dd HH:mm:ss");
						logDiv.innerHTML+="<font color='	#009ACD' size='1' style='font-weight: bold'>"+user_id+"</font><font color='#DC143C' size='1' style='font-weight: bold'>(群聊["+chatDatas[index].group_id+"]"+msgFlag+")</font>"+"<font color='#009ACD' size='1' style='font-weight: bold'>"+createTime+"</font><br>";
						logDiv.innerHTML+="<font color='#FFFFFF' size='1'>&nbsp;"+chatDatas[index].content+"</font><br>";
					}
				}
			}
			//其它信息处理;
			function OTHER(data){
				//处理数据
				log('OTHER')
				// logDiv.innerHTML+="<font color='green' size='1'>"+data+"</font><br>";
			}
			function getOnlineUserById(id){
				log('getOnlineUserById', id)
				var groups = curUser.groups;
				var onlineUserStr = "";
				for(var g = 0 ; g < groups.length ; g++){
					var group = groups[g];
					var users = group.users;
					for(var u = 0 ; u < users.length ; u++){
						var user = users[u];
						if(user.id == id){
							return user;
						}
					}
				}
			}
			function initOnlineUsers(){
				log('initOnlineUsers')
				var groups = curUser.groups;
				var onlineUserStr = "";
				for(var g = 0 ; g < groups.length ; g++){
					var group = groups[g];
					var users = group.users;
					onlineUserStr += "&nbsp;"+group.name+"在线成员("+users.length+"/"+users.length+")";
					for(var u = 0 ; u < users.length ; u++){
						var user = users[u];
						onlineUserStr +="<div id=\""+user.id+"\" nick=\""+user.nick+"\" style=\"line-height: 25px;margin: 5px 5px 0 5px;padding-left:15px;cursor:pointer;\" onclick=\"onlineDb(this);\" onmouseover=\"onlineMove(this);\"  onmouseleave=\"onlineLeave(this);\"><img alt=\""+user.id+"\" src=\""+user.avatar+"\" height=\"25px\" width=\"25px;\" style=\"float:left\">&nbsp;<font size='2'>"+user.nick+"("+user.id+")</font></div>";
					}
				}
				if(!onlineUserStr){
					onlineUserStr = "&nbsp;在线成员(0/0)";
				}
				document.getElementById("onlinePanel").innerHTML = onlineUserStr;
			}
		})


		//
	});

</script>
</body>

</html>